<script setup>
import {onMounted, reactive, ref} from 'vue'
import {ElMessage} from 'element-plus'
import {Delete, Edit, Plus, Search, View} from '@element-plus/icons-vue'
import http from "@/request/Http.js";

// 基础响应式数据
const loading = ref(false)
const tableData = ref([])
const multipleSelection = ref([])

// 搜索表单
const searchForm = reactive({username: ''})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// ========== 获取表格数据 ==========
const getTableData = async () => {
  loading.value = true
  try {
    const res = await http.get('/user/getUser', {
      params: {
        page: pagination.currentPage,
        pageSize: pagination.pageSize,
        username: searchForm.username
      }
    })
    if (res.code === 200) {
      tableData.value = res.data.records || []
      pagination.total = res.data.total || 0
    } else {
      ElMessage.error(res.msg || '获取数据失败')
    }
  } catch (err) {
    ElMessage.error('获取数据失败，请检查网络')
    console.error(err)
  } finally {
    loading.value = false
  }
}

// 搜索 & 重置
const handleSearch = () => {
  pagination.currentPage = 1
  getTableData()
}
const handleReset = () => {
  searchForm.username = ''
  pagination.currentPage = 1
  getTableData()
}

// ========== 新增用户 ==========
const addDialogVisible = ref(false)
const addForm = reactive({
  username: '',
  password: '',
  realname: '',
  email: '',
  phone: '',
  idCard: ''
})

const addFormRef = ref()

const addFormRules = {
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'},
    {min: 2, max: 20, message: '用户名长度应为 2~20 个字符', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {min: 6, message: '密码长度不能少于 6 位', trigger: 'blur'},
  ],
  email: [
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback()
        } else if (
            !/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/.test(value)
        ) {
          callback(new Error('请输入正确的邮箱格式'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  phone: [
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback()
        } else if (!/^1[3-9]\d{9}$/.test(value)) {
          callback(new Error('请输入正确的手机号格式'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const handleAdd = () => {
  addDialogVisible.value = true
}

const handleSubmitAdd = async () => {
  if (!addFormRef.value) {
    ElMessage.error('表单组件异常，请刷新页面')
    return
  }

  try {
    await addFormRef.value.validate()
    const response = await http.post('/user/addUser', addForm)
    if (response.code === 200) {
      ElMessage.success('新增成功')
      addDialogVisible.value = false
      resetAddForm()
      getTableData()
    } else {
      ElMessage.error(response.msg || '新增失败')
    }
  } catch (err) {
    console.error('表单校验失败：', err)
    ElMessage.error('请检查输入内容，如邮箱或手机号格式不正确')
  }
}

const resetAddForm = () => {
  Object.assign(addForm, {
    username: '',
    password: '',
    realname: '',
    email: '',
    phone: '',
    idCard: ''
  })
}

// ========== 编辑用户 ==========
const editDialogVisible = ref(false)
const editForm = reactive({
  id: null,
  username: '',
  realname: '',
  email: '',
  phone: '',
  idCard: '',
  avatar: ''
})

const editFormRef = ref()


// 编辑表单校验规则（只对可编辑的字段做验证）
const editFormRules = {
  realname: [
    {required: true, message: '请输入真实姓名', trigger: 'blur'}
  ],
  email: [
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback()
        } else if (
            !/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/.test(value)
        ) {
          callback(new Error('请输入正确的邮箱格式'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  phone: [
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback()
        } else if (!/^1[3-9]\d{9}$/.test(value)) {
          callback(new Error('请输入正确的手机号格式'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 头像上传成功回调
// 自定义头像上传方法
const customUpload = async (options) => {
  const file = options.file

  // 检查是否有用户ID
  if (!editForm.id) {
    ElMessage.error('请先保存用户基本信息后再上传头像')
    return
  }

  const formData = new FormData()
  formData.append('file', file)
  formData.append('userId', editForm.id.toString())

  try {
    console.log('开始上传头像...', '用户ID:', editForm.id)

    const res = await http.post('/user/uploadAvatar', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    })

    console.log('上传响应:', res.data)

    // 根据你的 DataVo 结构调整
    if (res && res.code === 200) {
      // 这里需要根据你的实际返回结构调整
      // 如果 res.data 直接是 URL 字符串
      editForm.avatar = res.data
      console.log('头像URL已更新:', editForm.avatar)
      ElMessage.success('头像上传成功')

      // 立即刷新表格数据，确保头像更新
      getTableData()
    } else {
      ElMessage.error(res.msg || '头像上传失败')
    }
  } catch (err) {
    console.error('上传失败：', err)
    ElMessage.error('头像上传失败，请重试')
  }
}

// 上传前校验
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('头像图片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('头像图片大小不能超过 2MB!')
    return false
  }
  return true
}

const handleEdit = (row) => {
  // 填充编辑表单数据
  Object.assign(editForm, {
    id: row.id,
    username: row.username,
    realname: row.realname || '',
    email: row.email || '',
    phone: row.phone || '',
    idCard: row.idCard || '',
    avatar: row.avatar || ''
  })
  editDialogVisible.value = true
}
const handleSubmitEdit = async () => {
  if (!editFormRef.value) {
    ElMessage.error('表单组件异常，请刷新页面')
    return
  }

  try {
    await editFormRef.value.validate()
    const response = await http.post('/user/updateUser', editForm)
    if (response.code === 200) {
      ElMessage.success('编辑成功')
      editDialogVisible.value = false
      getTableData()
    } else {
      ElMessage.error(response.msg || '编辑失败')
    }
  } catch (err) {
    console.error('表单校验失败：', err)
    ElMessage.error('请检查输入内容，如邮箱或手机号格式不正确')
  }
}


const resetEditForm = () => {
  Object.assign(editForm, {
    id: null,
    username: '',
    realname: '',
    email: '',
    phone: '',
    idCard: ''
  })
}

// ========== 查看用户 ==========
const viewDialogVisible = ref(false)
const viewForm = reactive({
  id: null,
  username: '',
  realname: '',
  email: '',
  phone: '',
  idCard: '',
  isVerified: 0,
  status: 0,
  createdAt: '',
  updatedAt: '',
  avatar: ''
})

const handleView = (row) => {
  Object.assign(viewForm, {
    id: row.id,
    username: row.username,
    realname: row.realname || '',
    email: row.email || '',
    phone: row.phone || '',
    idCard: row.idCard || '',
    isVerified: row.isVerified || 0,
    status: row.status || 0,
    createdAt: row.createdAt || '',
    updatedAt: row.updatedAt || '',
    avatar: row.avatar || ''
  })
  viewDialogVisible.value = true
}

// ========== 删除功能（包括单个和批量） ==========
const deleteDialogVisible = ref(false)
const deleteId = ref(null)
const deleteIds = ref([])

const handleDelete = (row) => {
  deleteId.value = row.id
  deleteDialogVisible.value = true
}

const handleBatchDelete = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要删除的数据')
    return
  }
  deleteIds.value = multipleSelection.value.map(item => item.id)
  deleteDialogVisible.value = true
}

const confirmDelete = async () => {
  try {
    let params = {}

    if (deleteId.value) {
      // 单个删除
      params = {id: deleteId.value}
    } else if (deleteIds.value && deleteIds.value.length > 0) {
      // 批量删除
      params = {ids: deleteIds.value.join(',')}
    }

    const response = await http.delete("/user/deleteUser", {params})
    if (response.code === 200) {
      ElMessage.success('删除成功')
      // 清空选择
      multipleSelection.value = []
      deleteDialogVisible.value = false
      deleteId.value = null
      deleteIds.value = []
      getTableData()
    } else {
      ElMessage.error(response.msg || '删除失败')
    }
  } catch (err) {
    ElMessage.error('删除失败，请重试')
    console.error(err)
  }
}

const cancelDelete = () => {
  deleteDialogVisible.value = false
  deleteId.value = null
  deleteIds.value = []
}

// ========== 分页相关 ==========
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  getTableData()
}
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  getTableData()
}

const handleSelectionChange = (selection) => {
  multipleSelection.value = selection
}

// 组件挂载
onMounted(() => {
  getTableData()
})
</script>

<template>
  <div class="user-manage">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
          v-model="searchForm.username"
          class="search-input"
          clearable
          placeholder="请输入用户名"
      >
        <template #prefix>
          <el-icon>
            <Search/>
          </el-icon>
        </template>
      </el-input>
      <el-button :icon="Search" type="primary" @click="handleSearch">搜索</el-button>
      <el-button @click="handleReset">重置</el-button>
    </div>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button :icon="Plus" type="primary" @click="handleAdd">新增用户</el-button>
      <el-button
          :disabled="multipleSelection.length === 0"
          :icon="Delete"
          type="danger"
          @click="handleBatchDelete"
      >
        批量删除 ({{ multipleSelection.length }})
      </el-button>
    </div>

    <!-- 用户表格 -->
    <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
    >
      <el-table-column align="center" type="selection" width="50"/>
      <el-table-column align="center" label="序号" type="index" width="60"/>

      <el-table-column label="头像" width="80">
        <template #default="{ row }">
          <div @click="console.log('表格头像URL:', row.avatar)">
            <el-image
                :src="row.avatar"
                fit="cover"
                style="width: 40px; height: 40px; border-radius: 50%;"
            >
              <template #error>
                <div
                    style="display: flex; align-items: center; justify-content: center; width: 40px; height: 40px; background: #f5f7fa; border-radius: 50%; color: #909399; font-size: 12px;">
                  无
                </div>
              </template>
            </el-image>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="用户名" prop="username" width="120"/>
      <el-table-column label="真实姓名" prop="realname" width="120"/>
      <el-table-column label="邮箱" prop="email" width="200"/>
      <el-table-column label="手机号" prop="phone" width="130"/>
      <el-table-column label="身份证号" prop="idCard" width="180"/>

      <el-table-column align="center" label="实名认证" prop="isVerified" width="100">
        <template #default="{ row }">
          <el-tag :type="row.isVerified === 1 ? 'success' : 'info'">
            {{ row.isVerified === 1 ? '已认证' : '未认证' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="状态" prop="status" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 0 ? 'success' : 'danger'">
            {{ row.status === 0 ? '正常' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="创建时间" prop="createdAt" width="180"/>

      <el-table-column label="更新时间" prop="updatedAt" width="180"/>

      <el-table-column align="center" fixed="right" label="操作" width="200">
        <template #default="{ row }">
          <el-button :icon="Edit" link size="small" type="primary" @click="handleEdit(row)">编辑</el-button>
          <el-button :icon="View" link size="small" type="info" @click="handleView(row)">查看</el-button>
          <el-button link size="small" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[5, 10, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 【新增用户】弹窗 -->
    <el-dialog v-model="addDialogVisible" title="新增用户" width="500px">
      <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="100px">
        <el-form-item label="用户名" required>
          <el-input v-model="addForm.username" placeholder="请输入用户名"/>
        </el-form-item>
        <el-form-item label="密码" required>
          <el-input v-model="addForm.password" placeholder="请输入密码" show-password type="password"/>
        </el-form-item>
        <el-form-item label="真实姓名">
          <el-input v-model="addForm.realname" placeholder="请输入真实姓名"/>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="addForm.email" placeholder="请输入邮箱"/>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="addForm.phone" placeholder="请输入手机号"/>
        </el-form-item>
        <el-form-item label="身份证号">
          <el-input v-model="addForm.idCard" placeholder="请输入身份证号"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitAdd">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 【编辑用户】弹窗 -->
    <el-dialog v-model="editDialogVisible" title="编辑用户" width="500px">
      <!-- 头像展示与上传 -->
      <div style="text-align: center; margin-bottom: 20px;">
        <el-upload
            :before-upload="beforeAvatarUpload"
            :http-request="customUpload"
            :show-file-list="false"
            class="avatar-uploader"
        >
          <img v-if="editForm.avatar" :src="editForm.avatar" class="avatar"
               style="width: 100px; height: 100px; border-radius: 50%; object-fit: cover;"/>
          <div v-else class="avatar-uploader-icon"
               style="width: 100px; height: 100px; border: 1px dashed #d9d9d9; border-radius: 50%; display: flex; align-items: center; justify-content: center; color: #8c939d;">
            <el-icon style="font-size: 28px;">
              <Plus/>
            </el-icon>
          </div>
        </el-upload>
        <div style="font-size: 12px; color: #999; margin-top: 5px;">
          点击上传新头像（建议尺寸 1:1）
        </div>
        <div v-if="!editForm.id" style="font-size: 12px; color: #e6a23c; margin-top: 5px;">
          提示：请先保存基本信息后再上传头像
        </div>
      </div>

      <!-- 编辑用户基本信息表单 -->
      <el-form ref="editFormRef" :model="editForm" :rules="editFormRules" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled placeholder="用户名不可修改"/>
        </el-form-item>
        <el-form-item label="真实姓名" required>
          <el-input v-model="editForm.realname" placeholder="请输入真实姓名"/>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="editForm.email" placeholder="请输入邮箱"/>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="editForm.phone" placeholder="请输入手机号"/>
        </el-form-item>
        <el-form-item label="身份证号">
          <el-input v-model="editForm.idCard" placeholder="请输入身份证号"/>
        </el-form-item>
      </el-form>

      <template #footer>
    <span class="dialog-footer">
      <el-button @click="editDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmitEdit">确定</el-button>
    </span>
      </template>
    </el-dialog>


    <!-- 【查看用户】弹窗 -->
    <el-dialog v-model="viewDialogVisible" title="查看用户" width="500px">
      <el-descriptions :column="1" border>
        <!-- 头像部分 - 添加点击放大功能 -->
        <el-descriptions-item label="头像">
          <div style="display: flex; align-items: center; gap: 10px;">
            <el-image
                :hide-on-click-modal="true"
                :initial-index="0"
                :preview-src-list="viewForm.avatar ? [viewForm.avatar] : []"
                :preview-teleported="true"
                :src="viewForm.avatar"
                :z-index="9999"
                fit="cover"
                style="width: 80px; height: 80px; border-radius: 50%; cursor: pointer;"
            >
              <template #error>
                <div
                    style="display: flex; align-items: center; justify-content: center; width: 80px; height: 80px; background: #f5f7fa; border-radius: 50%; color: #909399; font-size: 14px;">
                  无头像
                </div>
              </template>
              <template #placeholder>
                <div
                    style="display: flex; align-items: center; justify-content: center; width: 80px; height: 80px; background: #f5f7fa; border-radius: 50%; color: #909399; font-size: 14px;">
                  加载中...
                </div>
              </template>
            </el-image>
            <span v-if="viewForm.avatar" style="font-size: 12px; color: #666;">点击头像可放大查看</span>
          </div>
        </el-descriptions-item>

        <el-descriptions-item label="用户名">{{ viewForm.username }}</el-descriptions-item>
        <el-descriptions-item label="真实姓名">{{ viewForm.realname }}</el-descriptions-item>
        <el-descriptions-item label="邮箱">{{ viewForm.email }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ viewForm.phone }}</el-descriptions-item>
        <el-descriptions-item label="身份证号">{{ viewForm.idCard }}</el-descriptions-item>
        <el-descriptions-item label="实名认证">
          <el-tag :type="viewForm.isVerified === 1 ? 'success' : 'info'">
            {{ viewForm.isVerified === 1 ? '已认证' : '未认证' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="viewForm.status === 0 ? 'success' : 'danger'">
            {{ viewForm.status === 0 ? '正常' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ viewForm.createdAt }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ viewForm.updatedAt }}</el-descriptions-item>
      </el-descriptions>

      <template #footer>
    <span class="dialog-footer">
      <el-button @click="viewDialogVisible = false">关闭</el-button>
    </span>
      </template>
    </el-dialog>

    <!-- 删除确认弹窗 -->
    <el-dialog v-model="deleteDialogVisible" :before-close="cancelDelete" title="删除确认" width="400px">
      <div class="delete-content">
        <el-icon class="warning-icon" color="#E6A23C" size="24">
          <Warning/>
        </el-icon>
        <span>确定要删除选中的用户吗？此操作不可恢复！</span>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelDelete">取消</el-button>
          <el-button type="danger" @click="confirmDelete">确定删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.user-manage {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
}

.search-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  align-items: center;
}

.search-input {
  flex: 1;
}

.action-buttons {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.delete-content {
  display: flex;
  align-items: center;
  gap: 10px;
  color: #E6A23C;
  font-weight: 500;
}

.warning-icon {
  flex-shrink: 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>